#coding:utf8
from rest_framework import serializers
from django_redis import get_redis_connection
from redis import RedisError
import logging
logger = logging.getLogger('meiduo')

class RegisterSMSCodeSerializer(serializers.Serializer):

    text = serializers.CharField(label='验证码',max_length=4,min_length=4)
    image_code_id = serializers.UUIDField(label='图片唯一码')

    def validate(self, attrs):

        # 获取验证码
        text = attrs['text']
        #连接redis
        redis_conn = get_redis_connection('code')
        #获取redis中的验证码，同时删除记录
        redis_text = redis_conn.get('img_%s'%attrs['image_code_id'])

        if redis_text is None:
            raise serializers.ValidationError('验证码已过期')

        try:
            redis_conn.delete('img_%s'%attrs['image_code_id'])
        except RedisError as e:
            logger(e)
        #将验证码lower，注意： redis的值为bytes类型
        if text.lower() != redis_text.decode().lower():
            raise serializers.ValidationError('验证码不一致')

        return attrs